//订单表
const express=require('express')
const router=express.Router()
const pool=require('../utils/db')
const Response=require('../utils/Response')

//查询订单表  -- 用户id和订单id => SQL不会
router.post('/order-id',(req,res)=>{
    let {user_id} = req.body

    let sql = "select * from cyss_order where user_id=?"
    pool.query(sql,[user_id],(error,result) => {
        if(error) {
            res.send(Response.error(500,error))
            throw error
        }
        res.send(Response.ok(result))
    })
})

router.post('/orderId',(req,res)=>{
    let {orderId} = req.body

    let sql = 'select * from cyss_order where order_id=?'
    pool.query(sql,[orderId],(error,result)=>{
        if (error) {
            res.send(Response.error(500,error))
            throw error
        }
        res.send(Response.ok(result))
    })
})

//查询所有订单
router.get('/order-list',async (req,res)=>{
    let {page,pagesize} = req.query
    // console.log('查询订单列表参数',req.query);
    try {
        let startIndex= (page - 1) * pagesize
        let size= parseInt(pagesize)
        let sql ="select * from cyss_order limit ?,?"
        let result = await pool.querySync(sql,[startIndex,size])
        let sql2 = "select count(*) as count from cyss_order"
        let result2 = await pool.querySync(sql2,[startIndex,size])
        let total = result2[0].count
        // console.log('查询一结果：',result,);
        // console.log('查询二结果',result2);
        // console.log('result[0].count',total);
        res.send(Response.ok({page:parseInt(page),pagesize:size,total,result}))
    } catch (error) {
        res.send(Response.error(error))
    }
})

// 修改订单
router.post('/order-edit',(req,res) => {
    let { line_id,ordered_time,total_price,order_id,user_id } = req.body
    console.log(req.body);
    let sql = "update cyss_order set line_id=?,ordered_time=?,total_price=? where order_id=? and user_id=?"
    pool.query(sql,[line_id,ordered_time,total_price,order_id,user_id],(error,result) => {
        if(error) {
            res.send(Response.error(500,error))
            throw error
        }
        res.send(Response.ok(sql))
    })
})


//删除订单 
router.post('/order-del',(req,res)=>{
    let {id}=req.body
    
    let sql="delete from cyss_order where order_id=?"
    
    pool.query(sql,[id],(error,result)=>{
        if(error) {
            res.send(Response.error(500,error))
            throw error
        }
        res.send(Response.ok())
    })
})

//修改订单 ?存疑,我感觉不用修改,但是可能需要

//导出路由对象
module.exports=router